//app.js
const baseUrl = "https://life.tinydream.org/";
//const baseUrl = "http://localhost:81/";
App({
  onLaunch: function () {
    var token = wx.getStorageSync('token'),
      hasShop = wx.getStorageSync('hasShop'),
      that = this;
    console.log(token)
    if (!token) {
      // 登录
      wx.login({
        success: res => {
          that.request('api/wx/login', { code: res.code }, res1 => {
            console.log(res1)
            that.globalData.auth.token = res1.token
            wx.setStorageSync('token', res1.token)
            wx.setStorageSync('hasShop', res1.hasShop)
          });
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
        }
      })
    } else {
      that.globalData.auth.token = token;
      that.globalData.hasShop = hasShop
    }
    wx.request({
      url: baseUrl + 'api/api/qnUptoken',
      success(res){
        that.globalData.upToken = res.data.uptoken
      }
    })
  },
  globalData: {
    userInfo: null,
    auth: {token: '',},
    hasShop: false,
    upToken: ''
  },
  request(url, params, success, error) {
    wx.showLoading({
      title: "请求中。。。"
    })
    params = Object.assign(params, this.globalData.auth)
    let reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    if (!reg.test(url)) {
      url = baseUrl + url
    }
    // 网络请求
    wx.request({
      url: url,
      data: params,
      method: "POST",
      success(response) {
        let resData = response.data;
        if (resData.status == 0) {
          if ('function' == typeof success) {
            success(resData.data, resData.msg)
          } else {
            wx.showToast({
              title: resData.msg,
            })
          }
        } else {
          if ('function' == typeof error) {
            error(resData.msg)
          } else {
            wx.showToast({
              title: resData.msg || "",
              icon: "none"
            })
          }
        }
      },
      fail(){
        wx.showToast({
          title: '请求错误!',
          icon: "none"
        })
      },
      complete() {
        wx.hideLoading()
        // wx.showToast({
        //   title: '请求完成!',
        //   icon: "none"
        // })
      }
    })
  },
  getUserInfo(){
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        this.globalData.userInfo = res.userInfo
        this.request('api/wx/saveInfo', {}, function(data){

        });
      }
    })
  }
})